//
//  RootViewController.swift
//  ACFrameworkSwift_Example
//
//  Created by c5342925 on 2022/3/10.
//  Copyright © 2022 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import ACFrameworkSwift

/// 主入口
class RootViewController: UITableViewController, UISearchResultsUpdating {
    
    private lazy var titles: [String] = {
        return ["Dynamic Type",
                "Section-2",
                "Section-3",
                "Section-4"]
    }()
    
    private lazy var rowList: [[String]] = {
        return [["Font", "Color", "Theme"],
                ["case2-1", "case2-2"],
                ["case3-1", "case3-2"],
                ["case4-1", "case4-2"]]
    }()
    
    var displayTitles: [String] = []
    var displayRowList: [[String]] = []
    
    private let searchController = UISearchController(searchResultsController: nil)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        displayTitles = titles
        displayRowList = rowList
        
        // 注册字体，放在详情页中注册可能会存在延迟
        UIFont.registerFonts()
        
        navigationItem.title = "Test Cases"
        if #available(iOS 11.0, *) {
            setupSearchController()
            navigationItem.largeTitleDisplayMode = .automatic
            navigationItem.searchController = searchController
            navigationController?.navigationBar.prefersLargeTitles = true
        }
        
        setupTableView()
    }
    
    private func setupTableView() {
        self.tableView.estimatedRowHeight = 100
        #if swift(>=4.2)
        self.tableView.rowHeight = UITableView.automaticDimension
        #else
        self.tableView.rowHeight = UITableViewAutomaticDimension
        #endif
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "TESTCASECELL")
    }
    
    private func setupSearchController() {
        searchController.searchResultsUpdater = self
        // 在演示过程中模糊背景
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search Test Case"
    }
}

// MARK: - UITableViewDataSource & UITableViewDelegate

extension RootViewController {
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return displayTitles[section]
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 16
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return displayTitles.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return displayRowList[section].count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TESTCASECELL", for: indexPath)
        guard let textLabel = cell.textLabel else { return cell }
        textLabel.text = displayRowList[indexPath.section][indexPath.row]
        textLabel.numberOfLines = 0
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var name = "\(displayTitles[indexPath.section]) \(displayRowList[indexPath.section][indexPath.row]) VC"
        name = name.replacingOccurrences(of: " ", with: "")
        print("clike name = \(name)")
        var fullName = name
        if let bundleName = Bundle.main.bundleIdentifier, let appName = bundleName.split(separator: ".").last {
            fullName = "\(appName.replacingOccurrences(of: "-", with: "_")).\(name)"
        }
        guard let aClass = NSClassFromString(fullName) as? UIViewController.Type else {
//            preconditionFailure()
            printError("\(name) is not found")
            return
        }
        let vc = aClass.init()
        vc.title = name
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
	
// MARK: - UISearchResultsUpdating

extension RootViewController {
    
    func updateSearchResults(for searchController: UISearchController) {
        guard let queryString = searchController.searchBar.text, !queryString.isEmpty else {
            displayTitles = titles
            displayRowList = rowList
            tableView.reloadData()
            return
        }
        
        displayTitles.removeAll()
        displayRowList.removeAll()
        for (index, list) in rowList.enumerated() {
            // 不区分大小写匹配
            let cases = list.filter { $0.lowercased().contains(queryString.lowercased()) }
            if !cases.isEmpty {
                displayTitles.append(titles[index])
                displayRowList.append(cases)
            }
        }
        tableView.reloadData()
    }
}
